package com.google.gwt.sample.dynatablerf.client.home.presenter;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.sample.dynatablerf.shared.AppRequestFactory;
import com.google.gwt.sample.dynatablerf.shared.ProdutoProxy;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.IsWidget;

public class ProdutoCrudPresenter {

	private Display display;
	private ProdutoProxy proxy;
	private HasWidgets container;
	private AppRequestFactory request;
	
	public interface Display extends IsWidget {
		
		void copyTo(ProdutoProxy proxy);

		HasClickHandlers butaoSalvar();
		
	}
	
	public ProdutoCrudPresenter(Display display, AppRequestFactory appRequestFactory){
		
		this.display = display;
		this.request = appRequestFactory;
		createProxy();
		bind();
		
	}
	
	private void bind() {
		display.butaoSalvar().addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				display.copyTo(proxy);
				request.produtoRequest().persist(proxy);
				
				
			}
		});
	}

	private void createProxy() {
		proxy = request.produtoRequest().create(ProdutoProxy.class);
	}
	
	
	

	public void go(final HasWidgets hasWidgets){
		
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {

			@Override
			public void execute() {
				container = hasWidgets;
				hasWidgets.clear();
				hasWidgets.add(display.asWidget());

			}
		});
	}
}
